var CURRENT_POST_INDEX = 1;
var CHANGE_SPEED = 250;
var INTERVAL_ID = null;
var ROTATE_TIMEOUT = 9000; //miliseconds
var CAN_CHANGE = true; //flag used to stop changing slides until the previous slide is complete animeted

jQuery(document).ready(function($) {
	// Init the slideshow
	InitSlideshow();

	$(".slide-show-thumb").click(function(){
		// return if a slide is currently animating
		if (!CAN_CHANGE) return;
	
		clearInterval(INTERVAL_ID);
	
		// 1 based thumb index
		var nextThumbIndex = Number($(this).attr("id").split("-")[1]);
		if (nextThumbIndex == CURRENT_POST_INDEX)
			return;
		
		// Set next thumb's background color
		if (CURRENT_POST_INDEX == 0) CURRENT_POST_INDEX = 5
		$("#thumb-" + CURRENT_POST_INDEX).removeClass("thumb-hover");
		$(this).addClass("thumb-hover");
		
		// Hide the curent post and show the selected/next one
		HideCurrentPostAndShowNext(nextThumbIndex);
		
		// The current post becomes the selected/next one
		CURRENT_POST_INDEX = (nextThumbIndex  >= 5 ? 0 : nextThumbIndex);
		
		InitSlideshow();
	});
	
	function InitSlideshow(){
		INTERVAL_ID = setInterval(function(){$("#thumb-" + (CURRENT_POST_INDEX+1)).click();}, ROTATE_TIMEOUT);
	}
	
	function HideCurrentPostAndShowNext(nextPostIndex){
		var currentPost = $("#post-" + CURRENT_POST_INDEX);
		var nextPost = $("#post-" + nextPostIndex);
		
		CAN_CHANGE = false;
		$(currentPost).animate({ opacity: 0	}, CHANGE_SPEED, function(){
			// on complete animation
			$(currentPost).addClass("hide");
			$(nextPost).css("opacity", "0");
			$(nextPost).removeClass("hide");			
			$(nextPost).animate({ opacity: 1 }, CHANGE_SPEED );
			CAN_CHANGE = true;
		});
	}
});